package com.gyg.unsafeThreadDemo;

import lombok.SneakyThrows;

/**
 * 线程不安全情况二：银行取钱
 *
 * @author hxy
 */
public class NoSafeBank {
    public static void main(String[] args) {
        Account account = new Account(100, "投资基金");
        new Thread(new Bank(account, 50), "我").start();
        new Thread(new Bank(account, 100), "朋友").start();
    }
}

/**
 * 账户
 */
class Account {
    public int money;
    public String name;

    public Account(int money, String name) {
        this.money = money;
        this.name = name;
    }
}

/**
 * 银行
 */
class Bank implements Runnable {

    private Account account;
    private int drawingMoney;

    public Bank(Account account, int drawingMoney) {
        this.account = account;
        this.drawingMoney = drawingMoney;
    }

    @SneakyThrows
    @Override
    public void run() {

        //synchronized同步代码块，给对象加锁 synchronized(account)
        if (account.money - drawingMoney < 0) {
            System.out.println(Thread.currentThread().getName() + "-钱不够了！");
            return;
        } else {
            Thread.sleep(2000);
            account.money = account.money - drawingMoney;
            System.out.println(Thread.currentThread().getName() + "取到：" + drawingMoney + "，卡内余额：" + account.money);
        }

    }
}

